package com.boe.csb.core.common.utils;

import com.boe.csb.core.common.CsbConstants;
import com.ctc.ema.server.jwsserver.sms.MtMessage;
import com.ctc.ema.server.jwsserver.sms.MtMessageRes;
import org.apache.commons.lang3.StringUtils;
import org.apache.cxf.endpoint.Client;
import org.apache.cxf.jaxws.endpoint.dynamic.JaxWsDynamicClientFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.xml.namespace.QName;

/**
 * FIXME 待验证 --2016/12/24
 * 京东方通过webservice 调用短信接口
 * date 2016年12月19日
 * @author xc
 */
public class BoeMobileWSMsgSender implements IMobileMsgSender {
	
	private static final Logger logger = LoggerFactory.getLogger(BoeMobileWSMsgSender.class);
		
	private static String account;
	
	private static String password;//密码需要通过md5加密
	
	private static String smsType;
	
	private static String funcName;
	
	private static String regMsgTpl;
	
	private static String namespace;
	
	private Client client;

	private static BoeMobileWSMsgSender instance;

	private BoeMobileWSMsgSender(){
	}

	public static BoeMobileWSMsgSender getInstance(){
		if(instance == null){
			instance = new BoeMobileWSMsgSender();
			instance.init();
		}

		return instance;
	}
	
	public void init(){
		JaxWsDynamicClientFactory dcf = JaxWsDynamicClientFactory.newInstance(); 
	    client = dcf.createClient(CsbConstants.MOBILE_CALL_ENDPOINT);
	    namespace = CsbConstants.MOBILE_CALL_NAMESPACE;
	    password = MD5Utils.getMD5String(CsbConstants.MOBILE_CALL_PWD);
	    account = CsbConstants.MOBILE_CALL_ACCOUNT;
	    smsType = CsbConstants.MOBILE_CALL_SMSTYPE;
	    funcName = CsbConstants.MOBILE_CALL_FUNCNAME;
	    regMsgTpl = CsbConstants.MOBILE_REG_TEPL;
	}

	@Override
	public boolean sendRegVerifyCode(String code, String recNum) {
		MtMessage msg = new MtMessage();
		String[] revNums = new String[]{recNum};
		String content = getRegMsg(code);
		msg.setPhoneNumber(revNums);
		msg.setContent(content);
		
		QName qname;
	    try {
	    	qname = new QName(namespace, funcName);
	    	Object[] objs = client.invoke(qname, account, password, smsType, msg);
			logger.debug("调用boe短信网关返回:" + GsonUtils.object2String(objs) + ",recNum=" + recNum + ",code=" + code);
	    	if(objs.length > 0){
	    		MtMessageRes res = (MtMessageRes)objs[0];
				if(res != null) {
					String result = res.getSubStat();
					if(result != null && StringUtils.equals("000", result.split(":")[1])) {
						logger.debug("发送成功,result=" + GsonUtils.object2String(res));
						return true;
					}
				}
	    	}
	    	return false;
		} catch (Exception e) {
			logger.error("send msg to phone:" +  recNum + " error.", e);
			return false;
		}
	}
	
	private String getRegMsg(String code){
		return regMsgTpl.replace("${vcode}", code);
	}

}
